package com.yunji.ylexpiration.Controller;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.yunji.ylexpiration.config.AlipayConfig;
import com.yunji.ylexpiration.entity.FurnAddresstable;
import com.yunji.ylexpiration.entity.FurnCommodity;

import com.yunji.ylexpiration.entity.FurnOrders;
import com.yunji.ylexpiration.entity.FurnShoppinTrolley;
import com.yunji.ylexpiration.service.AddaddressService;
import com.yunji.ylexpiration.service.FurnCommodityService;
import com.yunji.ylexpiration.service.FurnOrdersMapperService;
import com.yunji.ylexpiration.service.FurnShoppinTrolleyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
public class FurnShoppinTrolleyController {
    @Autowired
    FurnCommodityService furnCommodityService;

    @Autowired
    FurnShoppinTrolleyService furnShoppinTrolleyService;

    @Autowired
    FurnOrdersMapperService furnOrdersMapperService;

    @Autowired
    private AddaddressService addaddressService;

    //    @RequestMapping(value = "/setCookies")
//    public  String setCookies(HttpServletResponse response , HttpServletRequest request ,Integer amount,Integer commid){
//        //HttpServerletRequest 装请求信息类
//        //HttpServerletRespionse 装相应信息的类
//        List<FurnShoppinTrolley> furnShoppinTrolleyslist=new ArrayList<> ();
//        commid=1;
//        FurnCommodity furnCommodity = furnCommodityService.selectByid (commid);//查询到该商品
//        if (null==furnCommodity){
//            return "";
//        }
//        FurnShoppinTrolley furnShoppinTrolley=new FurnShoppinTrolley ();
//        furnShoppinTrolley.setCommodityId (commid);
//        furnShoppinTrolley.setPrice (furnCommodity.getCommodityprices ());
//        furnShoppinTrolley.setTotal (furnCommodity.getCommodityprices ());
//        furnShoppinTrolley.setQuantity (1);
//        //大于一要改变数量与总价
//        amount=2;
//        if (amount>1){
//            furnShoppinTrolley.setQuantity (amount);
//            furnShoppinTrolley.setTotal (furnShoppinTrolley.getPrice ()*furnShoppinTrolley.getQuantity ());
//        }
//
//        Cookie cookie=new Cookie ("sessionId","3423325");
//        response.addCookie(cookie);
//
//        Cookie[] cookies =  request.getCookies();
//        if(cookies != null){
//            for(Cookie c : cookies){
//                if(c.getName().equals("sessionId")){
//                    System.out.println (c.getValue ());
//                    return c.getValue();
//                }
//            }
//        }
//        return "获得cookies信息成功";
//    }
    @RequestMapping("cartadd")
    @ResponseBody
    public boolean shopadd(Double price,Integer amount, Integer commid ,Integer cid,HttpSession session,HttpServletResponse response) throws IOException {
        response.setCharacterEncoding ("utf-8");
        Object userid= session.getAttribute("userid");
        if (null==userid){
            return false;
        }
        FurnShoppinTrolley furnShoppinTrolleys2 = furnShoppinTrolleyService.selfurnshoopingtrolleyByshooidbyuid (commid,1,cid);
        if (null!=furnShoppinTrolleys2) {
            Integer commodityId = furnShoppinTrolleys2.getCommodityId ();
            Integer colourId = furnShoppinTrolleys2.getColourId ();
            if (commodityId.equals(commid) && colourId.equals(cid)) {
                FurnShoppinTrolley furnShoppinTrolley = furnShoppinTrolleyService.selfurnshoopingtrolleyByid (furnShoppinTrolleys2.getId ());
                furnShoppinTrolley.setQuantity (furnShoppinTrolley.getQuantity () + amount);
                BigDecimal bg = new BigDecimal (furnShoppinTrolley.getPrice () * furnShoppinTrolley.getQuantity ());
                double f1 = bg.setScale (2, BigDecimal.ROUND_HALF_UP).doubleValue ();
                furnShoppinTrolley.setTotal (f1);
                furnShoppinTrolleyService.quantityadd (furnShoppinTrolleys2.getId (), furnShoppinTrolley);
                return true;
            }
        }else{
            FurnShoppinTrolley furnShoppinTrolley=new FurnShoppinTrolley ();
            furnShoppinTrolley.setCommodityId (commid);
            furnShoppinTrolley.setPrice (price);
            furnShoppinTrolley.setTotal (amount*price);
            furnShoppinTrolley.setQuantity (amount);
            furnShoppinTrolley.setUserId (Integer.valueOf (userid.toString ()));
            furnShoppinTrolley.setColourId (cid);
            //大于一要改变数量与总价
            if (amount>1){
                furnShoppinTrolley.setQuantity (amount);
                furnShoppinTrolley.setTotal (furnShoppinTrolley.getPrice ()*furnShoppinTrolley.getQuantity ());
            }
            int shoppinadd = furnShoppinTrolleyService.shoppinadd (furnShoppinTrolley);
            return true;
        }
        return true;
    }
    /**
     * 商品数量加一
     * @param shopid 购物车id
     */
    @RequestMapping("quantityadd")
    public @ResponseBody boolean quantityadd(Integer shopid , HttpSession session){
        Object userid = session.getAttribute ("userid");
        if (null!=userid) {
            FurnShoppinTrolley furnShoppinTrolley = furnShoppinTrolleyService.selfurnshoopingtrolleyByid (shopid);
            furnShoppinTrolley.setQuantity (furnShoppinTrolley.getQuantity () + 1);
            BigDecimal bg = new BigDecimal (furnShoppinTrolley.getPrice () * furnShoppinTrolley.getQuantity ());
            double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            furnShoppinTrolley.setTotal (f1);
            int quantitysubtract = furnShoppinTrolleyService.quantityadd (shopid, furnShoppinTrolley);
            return quantitysubtract>0;
        }else{
            return 0>1;
        }
    }

    //数量减一
    @RequestMapping("quantitysubtract")
    public @ResponseBody boolean quantitysubtract(Integer shopid){
        FurnShoppinTrolley furnShoppinTrolley = furnShoppinTrolleyService.selfurnshoopingtrolleyByid (shopid);
        furnShoppinTrolley.setQuantity (furnShoppinTrolley.getQuantity ()-1);
        BigDecimal bg = new BigDecimal (furnShoppinTrolley.getPrice ()*furnShoppinTrolley.getQuantity ());
        double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        furnShoppinTrolley.setTotal(f1);
        int quantitysubtract = furnShoppinTrolleyService.quantitysubtract (shopid, furnShoppinTrolley);
        return quantitysubtract>0;
    }
    //购物车根据id删除
    @RequestMapping("delshoop")
    public @ResponseBody boolean delshoop(Integer shopid){
        int i = furnShoppinTrolleyService.delfurnshoopingtrolleyByid (shopid);
        return i>0;
    }
    //查询数据库的数据
    @RequestMapping("selcart.html")
    public  String cart(HttpSession session, Model model){
        Object userid = session.getAttribute ("userid");
        if (null!=userid){
            List<FurnShoppinTrolley> trolleyList = furnShoppinTrolleyService.selfurnshoopingtrolleyByuserid ((Integer) userid);
            model.addAttribute("shoop",trolleyList);
        }
        return "cart";
    }
    //删除多个商品
    @RequestMapping("delshoopduo")
    @ResponseBody
    public boolean delshoopduo(String shopid){
        int i1 =0;
        String[] ss2 = shopid.split(",");//使用字符串逗号 ,切割字符串
        for(int i = 0; i <ss2.length ; i++) {
            i1 = furnShoppinTrolleyService.delfurnshoopingtrolleyByid (Integer.valueOf (ss2[i]));
        }
        return  i1>0;
    }
    @RequestMapping("jons.html")
    public String jsorder2( Integer amount, Integer commid,String price ,Integer cid ,HttpSession session, Model model){
        FurnCommodity furnCommodity = furnCommodityService.selectByid (commid);
        Double sum=Double.valueOf (price)*amount;
        model.addAttribute ("furnCommodity",furnCommodity);
        Object a =session.getAttribute("userid");
        List<FurnAddresstable>furnAddresstables=addaddressService.seleuid(Integer.valueOf(String.valueOf(a)));
        model.addAttribute("furnAddresstables",furnAddresstables);
        model.addAttribute ("ColourId",cid);
        model.addAttribute ("CommodityId",commid);
        model.addAttribute ("sum",sum);
        session.setAttribute ("count",1);
        model.addAttribute ("name",furnCommodity.getProductname ());
        return "order2";
    }
    @RequestMapping("jsorder.html")
    public String closeAnAccount(String ck ,Model model,HttpSession session){
        List<FurnShoppinTrolley> list=new ArrayList<> ();
        String[] ss2 = ck.split(",");//使用字符串逗号 ,切割字符串
        double sum=0;
        Integer count=0;
        FurnShoppinTrolley furnShoppinTrolley1 =null;
        for(int i = 0; i <ss2.length ; i++) {
            furnShoppinTrolley1 = furnShoppinTrolleyService.selfurnshoopingtrolleyByshooid (Integer.valueOf (ss2[i]));
            list.add (furnShoppinTrolley1);
            FurnShoppinTrolley furnShoppinTrolley  = furnShoppinTrolleyService.selfurnshoopingtrolleyByid (Integer.valueOf (ss2[i]));
            sum+=furnShoppinTrolley.getTotal();
            count+=furnShoppinTrolley.getQuantity ();
        }
        Object a =session.getAttribute("userid");
        List<FurnAddresstable>furnAddresstables=addaddressService.seleuid(Integer.valueOf(String.valueOf(a)));
        model.addAttribute("furnAddresstables",furnAddresstables);
        model.addAttribute ("list",list);
        model.addAttribute ("sum",sum);
        model.addAttribute ("ck",ck);
        session.setAttribute ("count",count);
        model.addAttribute ("name",furnShoppinTrolley1.getFurnCommodities ().getProductname ());
        return "order";
    }
    @RequestMapping("FurnOrders")
    public String FurnOrdersadd(String ck,double sum,String name,HttpSession session){
        String orderId = UUID.randomUUID().toString();
        String[] ss2 = ck.split(",");//使用字符串逗号 ,切割字符串
        Object userid = session.getAttribute ("userid");
        Object count = session.getAttribute ("count");
        String ColourId="";
        String commodityId="";
        Date date=new Date ();
        for (int i = 0; i <ss2.length ; i++) {
            FurnShoppinTrolley furnShoppinTrolley = furnShoppinTrolleyService.selfurnshoopingtrolleyByshooid (Integer.valueOf (ss2[i]));
            ColourId+= furnShoppinTrolley.getColourId ()+",";
            commodityId+=furnShoppinTrolley.getCommodityId ()+",";
        }
        //删除购物车结算商品
        for(int i = 0; i <ss2.length ; i++) {
            furnShoppinTrolleyService.delfurnshoopingtrolleyByid(Integer.valueOf (ss2[i]));
        }
        FurnOrders furnOrders=new FurnOrders ();
        furnOrders.setOrderNum (orderId);
        furnOrders.setOrderStatus(String.valueOf (10));
        furnOrders.setBuyCounts (Integer.valueOf (count.toString ()));
        furnOrders.setOrderAmount (sum);
        furnOrders.setClassificationtypeId (ColourId);
        furnOrders.setUserId (Integer.valueOf (userid.toString ()));
        furnOrders.setCommodityId (commodityId);
        furnOrders.setCreatetime (date);
        furnOrders.setAddresstableId (1);
        int i = furnOrdersMapperService.FurnOrdersadd (furnOrders);
        session.setAttribute ("orderNum",orderId);
        session.setAttribute ("sum",sum);
        session.setAttribute ("name",name);
        if (i<0){
            return "";
        }else{
            return "redirect:http://localhost:8080/goAlipay";
        }
    }

    @RequestMapping("FurnOrdersadd2")
    public String FurnOrdersadd2(double sum ,String name ,Integer ColourId,Integer CommodityId, HttpSession session){
        String orderId = UUID.randomUUID().toString();
        Object userid = session.getAttribute ("userid");
        Date date=new Date ();
        FurnOrders furnOrders=new FurnOrders ();
        furnOrders.setOrderNum (orderId);
        furnOrders.setOrderStatus(String.valueOf (10));
        furnOrders.setOrderAmount (sum);
        furnOrders.setClassificationtypeId (ColourId.toString ());
        furnOrders.setUserId (Integer.valueOf (userid.toString ()));
        furnOrders.setCommodityId (CommodityId.toString ());
        furnOrders.setCreatetime (date);
        furnOrders.setAddresstableId (1);
        furnOrders.setBuyCounts (1);
        int i = furnOrdersMapperService.FurnOrdersadd (furnOrders);
        session.setAttribute ("orderNum",orderId);
        session.setAttribute ("name",name);
        session.setAttribute ("sum",sum);

        if (i<0){
            return "";
        }else{
            return "redirect:http://localhost:8080/goAlipay";
        }
    }

    @RequestMapping("huitiao")
    public String huitiao(HttpSession session,Model model){
        FurnOrders furnOrders =new FurnOrders ();
        furnOrders.setOrderNum (String.valueOf (session.getAttribute("orderId")));
        furnOrders.setOrderStatus (String.valueOf (20));
        int i = furnOrdersMapperService.upFurnOrders (furnOrders);
        if (i<0){
            return"";
        }else {
            List<FurnCommodity> furnCommodities05 = furnCommodityService.RelatedByLimit15(null, null, 0, 5);
            List<FurnCommodity> furnCommodities510 = furnCommodityService.RelatedByLimit15(null, null, 5, 5);
            List<FurnCommodity> furnCommodities105 = furnCommodityService.RelatedByLimit15(null, null, 10, 5);
            model.addAttribute("furnCommodities05",furnCommodities05);
            model.addAttribute("furnCommodities510",furnCommodities510);
            model.addAttribute("furnCommodities105",furnCommodities105);
            return"ok";
        }
    }
    //订单管理未支付去支付
    @RequestMapping("goAlipay2")
    public String goAlipay2(String orderNum,HttpSession session){
        session.setAttribute ("orderNum",orderNum);
        FurnOrders furnOrders = furnOrdersMapperService.selFurnOrdersnum (orderNum);
        session.setAttribute ("sum",furnOrders.getOrderAmount ());
        String comm=furnOrders.getCommodityId ();
        String[] ss2 = comm.split(",");
        FurnCommodity furnCommodity = furnCommodityService.selectByid (Integer.valueOf (ss2[0]));
        session.setAttribute ("name",furnCommodity.getProductname ());
        return "redirect:http://localhost:8080/goAlipay";
    }
    @RequestMapping("/goAlipay")
    public void goAlipay(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        String orderNum =String.valueOf (session.getAttribute ("orderNum"));
        session.setMaxInactiveInterval(30*60);
        session.setAttribute("orderId", orderNum);
        // 获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient (AlipayConfig.gatewayUrl, AlipayConfig.app_id,
                AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key,
                AlipayConfig.sign_type);
        // 设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = orderNum;
        //付款金额，必填
        String total_amount =String.valueOf (session.getAttribute ("sum"));
        //订单名称，必填
        String subject = session.getAttribute ("name")+"等";
        //商品描述，可空
        String body = "";

        // 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。
        // 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
        String timeout_express = "1c";

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\"," + "\"total_amount\":\"" + total_amount
                + "\"," + "\"subject\":\"" + subject + "\"," + "\"body\":\"" + body + "\"," + "\"timeout_express\":\""
                + timeout_express + "\"," + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        // 请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(result);
    }
    @RequestMapping("count.html")
    @ResponseBody
    public int count(HttpSession session){
        Object userid = session.getAttribute ("userid");
        int furnshoppcount =0;
        if (null!=userid){
            furnshoppcount = furnShoppinTrolleyService.furnshoppcount (Integer.valueOf (userid.toString ()));
        }
        return furnshoppcount;
    }
}